package com.test.simplechat.server;


import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.test.simplechat.config.WebConstants;
import com.test.simplechat.model.WebChatModel;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpUtil;
import io.netty.handler.codec.http.websocketx.*;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.util.CharsetUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;

/**
 * 消息处理
 *
 * @author wen
 */
public class MyWebSocketHandler extends SimpleChannelInboundHandler<Object> {

    private final static Logger LOGGER = LoggerFactory.getLogger(MyWebSocketHandler.class);

    private String wsPath;
    private WebSocketServerHandshaker handshaker;

    public MyWebSocketHandler(String wsPath) {
        this.wsPath = wsPath;
    }

    public MyWebSocketHandler() {
    }

    private static void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res) {
        // 返回应答给客户端
        if (res.status().code() != HttpResponseStatus.OK.code()) {
            ByteBuf buf = Unpooled.copiedBuffer(res.status().toString(), CharsetUtil.UTF_8);
            res.content().writeBytes(buf);
            buf.release();
            HttpUtil.setContentLength(res, res.content().readableBytes());
        }

        // 如果是非Keep-Alive，关闭连接
        ChannelFuture f = ctx.channel().writeAndFlush(res);
        if (!HttpUtil.isKeepAlive(req) || res.status().code() != HttpResponseStatus.OK.code()) {
            f.addListener(ChannelFutureListener.CLOSE);
        }
    }

    public String getWsPath() {
        return wsPath;
    }

    public void setWsPath(String wsPath) {
        this.wsPath = wsPath;
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        String leaveUid = ctx.channel().attr(WebConstants.CHANNEL_UUID_KEY).get();
        if (leaveUid != null && !"".equals(leaveUid)) {
            leaveUid = java.net.URLDecoder.decode(leaveUid, "UTF-8");
            LOGGER.debug("客户端{}断开连接，通道关闭！", leaveUid);
            //添加到channelGroup 通道组
            MyChannelHandlerPool.CHANNEL_ID_MAP.remove(leaveUid);
            MyChannelHandlerPool.channelGroup.remove(ctx.channel());
        }
        //在线人数统计
        int onlineUserCount = MyChannelHandlerPool.CHANNEL_ID_MAP.keySet().size();
        LOGGER.debug("在线人数:{}", onlineUserCount);
        MyChannelHandlerPool.CHANNEL_ID_MAP.keySet().stream().forEach(i -> System.out.println(i));
        WebChatModel chatModel = null;
        if (leaveUid != null && !"".equals(leaveUid)) {
            chatModel = new WebChatModel(leaveUid, "", leaveUid + "下线", onlineUserCount, WebConstants.MSG_TYPE_PUB);
        }
        if (chatModel != null) {
            GsonBuilder gsonbuilder = new GsonBuilder();
            gsonbuilder.serializeNulls();
            Gson gson = gsonbuilder.create();
            MyChannelHandlerPool.channelGroup.writeAndFlush(new TextWebSocketFrame(gson.toJson(chatModel)));
        }
    }

    //收到信息后，群发给所有channel
    private void sendAllMessage(String message) {
        MyChannelHandlerPool.channelGroup.writeAndFlush(new TextWebSocketFrame(message));

    }


    //单发
    private void sendMessage(ChannelHandlerContext ctx, String message) {
        ctx.writeAndFlush(new TextWebSocketFrame(message));
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
//// 传统的HTTP接入
//        if (msg instanceof FullHttpRequest) {
//            handleHttpRequest(ctx, (FullHttpRequest) msg);
//        }
        // WebSocket接入
        if (msg instanceof WebSocketFrame) {
            handleWebSocketFrame(ctx, (WebSocketFrame) msg);
        }
    }

    //ping、pong
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
//        LOGGER.debug("触发:{}",evt);
        //用于触发用户事件，包含触发读空闲、写空闲、读写空闲
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent event = (IdleStateEvent) evt;
            if (event.state() == IdleState.ALL_IDLE) {
                Channel channel = ctx.channel();
                //关闭无用channel，以防资源浪费
                channel.close();
            }
        }
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

    private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) {

        // 判断是否是关闭链路的指令
        if (frame instanceof CloseWebSocketFrame) {
            handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain());
            return;
        }
        // 判断是否是Ping消息
        if (frame instanceof PingWebSocketFrame) {
            ctx.channel().write(new PongWebSocketFrame(frame.content().retain()));
            return;
        }
        // 本例程仅支持文本消息，不支持二进制消息
        if (!(frame instanceof TextWebSocketFrame)) {
            throw new UnsupportedOperationException(
                    String.format("%s frame types not supported", frame.getClass().getName()));
        }
        int onlineUserCount = MyChannelHandlerPool.CHANNEL_ID_MAP.keySet().size();
        // 返回应答消息
        String request = ((TextWebSocketFrame) frame).text();
        GsonBuilder gsonbuilder = new GsonBuilder();
        gsonbuilder.serializeNulls();
        Gson gson = gsonbuilder.create();
        WebChatModel chatModel = gson.fromJson(request, WebChatModel.class);
        chatModel.setOnlineUserCount(onlineUserCount);
        chatModel.setCurrentTime(new Date());
        chatModel.setType(WebConstants.MSG_TYPE_PRI);
        Channel currentUserChannel = ctx.channel();
        MyChannelHandlerPool.channelGroup.writeAndFlush(new TextWebSocketFrame(gson.toJson(chatModel)));

    }
}
